# -*- coding: UTF-8 -*-
# @Author  : icedew
# @File    : forms.py
# @Time    : 2019-4-29 18:37
from flask_wtf import FlaskForm
from wtforms import Form, StringField, IntegerField, BooleanField, PasswordField, SubmitField
from wtforms.validators import Email, InputRequired, Length, EqualTo, DataRequired, ValidationError

from apps.cms.models import CMSUser
from apps.forms import BaseForm

#
# class LoginForm(BaseForm):
#     email = StringField("邮箱",validators=[Email(message='请输入正确的邮箱格式'),
#                                     InputRequired(message='请输入邮箱')])
#     password = StringField("密码",validators=[Length(6, 20, message='密码长度不够或超出')])
#     remember = IntegerField()
from apps.utils import xcache


class LoginForm(FlaskForm):
    email = StringField("邮箱", validators=[DataRequired(),Email(),Length(1,64)],render_kw = {"placeholder": "邮箱"})
    password = PasswordField("密码", validators=[DataRequired()],render_kw = {"placeholder": "密码"})
    remember_me = BooleanField("记住我")
    submit = SubmitField("登录")


class ResetPwdForm(BaseForm):
    oldpwd = StringField(validators=[Length(6,30, message='密码长度6-30')])
    newpwd = StringField(validators=[Length(6,30, message='密码长度6-30')])
    newpwd2 = StringField(validators=[EqualTo('newpwd', message='新密码输入不一致')])

class RestEmailForm(BaseForm):
    email = StringField(validators=[Email(message='邮箱格式错误'),InputRequired(message='请输入邮箱') ])
    captcha = StringField(validators=[Length(min=6, max=6, message='验证码长度错误')])

    def validate_email(self, field):
        user = CMSUser.query.filter_by(email=field.data).first()
        if user:
            raise ValidationError('该邮箱已存在')

    def validate_captcha(self, field):
        email = self.email.data
        captcha = field.data
        captcha_cache = xcache.get(email)
        #判断memcached中是否有对应的邮箱及验证码，小写进行比较，这样用户可以不区分大小写
        if  not captcha_cache or captcha.lower() != captcha_cache.lower():
            raise ValidationError('邮箱验证码错误')